#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
# from html import escape
from HTMLTable import (HTMLTable)

from ctools.common.strhelper import (indent_str,)

import logging
from ctools.logext import *

tname = os.path.basename(os.path.realpath(__file__))
tlog = logging

def _formate_html(html:str):
    _deepth = 0
    _html = ''
    left, right = 0, 0
    is_td = False

    linebreak = '<br/>'
    html = html.replace('\n', linebreak)
    while left < len(html) - 1:
        tmp = left
        left = html.find('<', tmp)
        right = html.find('>', left)
        if left < 0 or right < 0:
            break

        if html[left:right+1] == '<br/>':
            _html += html[tmp:right+1]
            left = right+1
            continue

        if html[left+1] ==    '/':
            _deepth -= 1
        if is_td:
            is_td = False
            _html += html[tmp:right+1]
        else:
            _html += indent_str(_deepth, html[tmp:right+1])

        if html[left+1] !=    '/':
            _deepth += 1
        xxx = ('<td', '<th')
        for x in xxx:
            if x in html[tmp:right+1]:
                is_td = True
        if not is_td:
            _html += '\n'
        left = right+1
    return _html.replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"')

class MyHTMLTable(HTMLTable):
    def __init__(self, caption='', rows=()):
        super().__init__(caption, rows)
        self._header_rows = 0

    def to_html(self, with_hader=True):
        if with_hader or (not self.have_header):
            return _formate_html(super().to_html())
        # TODO: use HTMLTable.to_html_inner_chips()?
        return _formate_html(super().to_html())

    def append_header_rows(self, rows):
        self._header_rows += len(rows)
        return super().append_rows(rows=rows, is_header=True)

    def add_row(self, row: list|tuple, *, style={}, **kwargs):
        return super().append_rows((row,), is_header=False)

    def get_column_index(self, index:int):
        name = self.index2colname.get(index, None)
        if name:
            return self.get_column(name)
        return None

    @property
    def row_col_num(self):
        return len(self), len(self[0])

    @property
    def have_header(self):
        return bool(self._header_rows)
